import requests
import json
import base64
import pickle
import time
import sys

import threading



def set_data(name:str,data:object,debug=False):
    t0=time.time()
    url = "http://localhost:4000/jsonrpc"
    data_b64=base64.b64encode(pickle.dumps(data)).decode('ascii')
    # Example echo method
    
    payload = {
        "method": "set_data",
        "params": [name,data_b64],
        "jsonrpc": "2.0",
        "id": 0,
    }
    response = requests.post(url, json=payload).json()
    t1=time.time()
    if debug:
        print(response)
        print('set value,time elapsed',t1-t0,'size is %f MB'%(sys.getsizeof(data_b64)*1.0/(1024*1024*1.0)),'\n\n')

def get_data(name:str,debug=False):
    t0=time.time()
    url = "http://localhost:4000/jsonrpc"

    # Example echo method
    payload = {
        "method": "get_data",
        "params": [name],
        "jsonrpc": "2.0",
        "id": 0,
    }
    response = requests.post(url, json=payload).json()
    t1=time.time()
    resp_bytes = response['result'].encode('ascii')
    pkl_bytes = base64.b64decode(resp_bytes)
    data = pickle.loads(pkl_bytes)
    
    
    t2 = time.time()
    if debug:
        hash(response['result'])
        t3 = time.time()
        print('get value,time elapsed:\n','request:',t1-t0,'total:',t2-t0,'\ndecoding:',t2-t1,'hashing:',t3-t2)
        print(data,'\n','size is %f MB'%(sys.getsizeof(response['result'])*1.0/(1024*1024*1.0)))
        print('')
    return data

def get_last_refresh_time():
    t0=time.time()
    url = "http://localhost:4000/jsonrpc"
    payload = {
        "method": "get_last_refresh_time",
        "jsonrpc": "2.0",
        "id": 0,
    }
    response = requests.post(url, json=payload).json()
    print(response,response['result'])
    return response['result']


class Client():
    def __init__(self):
        self.on_data_refreshed = lambda self: None
        th=threading.Thread(target = self._get_command_loop)
        th.setDaemon(True)
        th.start()
        
        
    def _get_command_loop(self):
        last_refresh_time = 0
        while(1):
            time.sleep(1)
            refresh_time_tmp = self.get_last_refresh_time()
            if last_refresh_time<refresh_time_tmp-0.2:
                last_refresh_time = refresh_time_tmp
                print("exec commnd!")
                self.on_data_refreshed(self)
            print(last_refresh_time)
    
    def get_last_refresh_time(self):
        return get_last_refresh_time()
        
    def set_data(self,name:str,data:object):
        set_data(name,data)
        
    def get_data(self,name):
        return get_data(name)

if __name__ == "__main__":
    c=Client()
    
    c.on_data_refreshed=lambda self:print(self.get_data('a'))
    c.set_data('a','hhhhhhhhhhhhhhhhhh')
    c.get_data('a')
    c.set_data('b',[1,2,3])# 模拟，传输一张较大的图片。
    last = c.get_last_refresh_time()
    print(last)
    print(c.get_data('b'))
    while(1):
        time.sleep(1)
